/* eslint-disable no-undef */
/* global window */
import modelExtend from 'dva-model-extend'
import queryString from 'query-string'
import { sum, excel } from 'services/transactionStatistics'
import { listall } from 'services/sysUser'
import { listall as listCodeAll } from 'services/basicData'
import downBlobFile from 'utils/downBlobFile'
import { message } from 'antd'
import { pageModel } from './common'

export default modelExtend(pageModel, {
  namespace: 'transactionStatistics',
  state: {
    userListAll: [],
    codeListAll: [],
  },
  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/transactionstatistics') {
          const payload = queryString.parse(location.search) || { page: 1 }
          dispatch({
            type: 'list',
            payload,
          })
          dispatch({
            type: 'listAllUser',
          })
          dispatch({
            type: 'listAllCode',
            payload: {
              type: 'Currencies',
            },
          })
        }
      })
    },
  },
  effects: {
    * list ({ payload = {} }, { call, put }) {
      const data = yield call(sum, payload)
      const listData = data.data
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: listData.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: listData.total,
            },
          },
        })
        message.success('get success')
      } else {
        message.error(data.msg || data.message)
      }
    },
    * excel ({ payload = {} }, { call }) {
      const data = yield call(excel, payload)
      if (data.success) {
        message.success('excel success')
        let blob = new Blob([data.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
        downBlobFile(blob, 'transaction_statistics.xlsx')
      } else {
        message.error(data.msg)
      }
    },
    * listAllUser ({ payload = {} }, { call, put }) {
      const data = yield call(listall, payload)
      if (data.success) {
        yield put({
          type: 'updateSelectState',
          payload: {
            userListAll: data.data,
          },
        })
      }
    },
    * listAllCode ({ payload = {} }, { call, put }) {
      const data = yield call(listCodeAll, payload)
      if (data.success) {
        yield put({
          type: 'updateSelectState',
          payload: {
            codeListAll: data.data,
          },
        })
      }
    },
  },
})

